# coding=utf-8
__author__ = 'linzh'

import pycurl
import StringIO
import urllib

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info(__name__)


class CoCurl(object):
    DEBUG = False
    AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"

    def __init__(self, host, port=80, debug=False, ssl=False):
        self.host = host
        self.port = port
        self.header = None
        if ssl:
            scheme = 'https://'
            port = 443
        else:
            scheme = 'http://'

        if not port or port == 80 or str(port) == "80":
            self.url = scheme + host
        else:
            self.url = scheme + host + ':' + str(port)

        logger.info(host)
        logger.info(port)

        self.client = pycurl.Curl()

        if self.DEBUG:
            self.client.setopt(pycurl.USERAGENT, self.AGENT)
            self.client.setopt(pycurl.PROXY, "http://192.168.248.152:8888")

    def set_header(self, header):
        header_list = list()
        for k in header:
            print k
            header_list.append(k + ':' + str(header[k]))

        self.header = header
        self.client.setopt(pycurl.HTTPHEADER, header_list)

    def ver(self):
        return pycurl.version_info()

    def get(self, url):
        http_url = self.url + url

        c = self.client

        b = StringIO.StringIO()

        c.setopt(pycurl.URL, http_url)
        c.setopt(pycurl.CUSTOMREQUEST, "GET")
        c.setopt(pycurl.WRITEFUNCTION, b.write)
        c.setopt(pycurl.POSTFIELDS, "")

        try:
            # 执行请求
            c.perform()
        except Exception, err:
            print err
        rtn = dict()
        rtn['code'] = c.getinfo(pycurl.HTTP_CODE)
        rtn['data'] = b.getvalue()
        return rtn

    def post(self, path, param):
        """
        """
        http_url = self.url + path

        self.client.setopt(pycurl.URL, http_url)
        self.client.setopt(pycurl.CUSTOMREQUEST, "POST")
        buff = StringIO.StringIO()

        self.client.setopt(pycurl.WRITEDATA, buff)

        if isinstance(param, str):
            post_data = param
        elif isinstance(param, dict):
            post_data = urllib.urlencode(param)

        # 如果param是字符串，则使用表单提交方式
        self.client.setopt(pycurl.POSTFIELDS, post_data)

        self.client.perform()

        rtn = dict()
        rtn['code'] = self.client.getinfo(pycurl.HTTP_CODE)
        rtn['data'] = buff.getvalue()
        return rtn

    def put(self, path, param):
        """
        """
        http_url = self.url + path

        self.client.setopt(pycurl.URL, http_url)
        self.client.setopt(pycurl.CUSTOMREQUEST, "PUT")
        buff = StringIO.StringIO()

        self.client.setopt(pycurl.WRITEDATA, buff)

        if isinstance(param, str):
            post_data = param
        elif isinstance(param, dict):
            post_data = urllib.urlencode(param)
        else:
            post_data = ""

        # 如果param是字符串，则使用表单提交方式
        self.client.setopt(pycurl.POSTFIELDS, post_data)

        self.client.perform()

        rtn = dict()
        rtn['code'] = self.client.getinfo(pycurl.HTTP_CODE)
        rtn['data'] = buff.getvalue()

        return rtn

    def patch(self, path, param):
        http_url = self.url + path

        c = self.client
        self.client.setopt(pycurl.URL, http_url)

        buff = StringIO.StringIO()
        self.client.setopt(pycurl.WRITEDATA, buff)

        c.setopt(pycurl.CUSTOMREQUEST, "PATCH")

        if isinstance(param, str):
            post_data = param
        elif isinstance(param, dict):
            post_data = urllib.urlencode(param)
        else:
            post_data = ""

        # 如果param是字符串，则使用表单提交方式
        self.client.setopt(pycurl.POSTFIELDS, post_data)

        self.client.perform()

        rtn = dict()
        rtn['code'] = self.client.getinfo(pycurl.HTTP_CODE)
        rtn['data'] = buff.getvalue()
        return rtn

    def delete(self, path, param=""):
        http_url = self.url + path
        buff = StringIO.StringIO()
        c = self.client
        c.setopt(pycurl.URL, http_url)
        c.setopt(pycurl.WRITEDATA, buff)
        c.setopt(pycurl.CUSTOMREQUEST, "DELETE")
        c.setopt(pycurl.POSTFIELDS, param)
        c.perform()
        rtn = dict()
        rtn['code'] = self.client.getinfo(pycurl.HTTP_CODE)
        rtn['data'] = buff.getvalue()
        return rtn

    def status(self, url, ts=2):
        """
        测试web状态
        默认在2秒内进行
        """
        http_url = self.url + url
        c = self.client
        b = StringIO.StringIO()
        c.setopt(pycurl.URL, http_url)

        # 设置超时时间
        c.setopt(pycurl.CONNECTTIMEOUT, ts)
        c.setopt(pycurl.WRITEFUNCTION, b.write)

        # 执行请求
        c.perform()

        code = c.getinfo(pycurl.HTTP_CODE)

        return code

    def file(self, url, param):
        """
        文件上传
        """
        pass

    def upload_files(self, path, file_path, params, file_key='fileUpload'):
        """
        """
        http_url = self.url + path

        self.client.setopt(pycurl.URL, http_url)

        buff = StringIO.StringIO()

        self.client.setopt(pycurl.WRITEDATA, buff)

        post_body = list()

        for k in params:
            post_body.append((k, str(params[k])))

        post_body.append((file_key, (self.client.FORM_FILE, file_path)))

        self.client.setopt(self.client.HTTPPOST, post_body)

        self.client.perform()

        rtn = dict()
        rtn['code'] = self.client.getinfo(pycurl.HTTP_CODE)
        rtn['data'] = buff.getvalue()
        return rtn

    def post_with_host(self):
        pass

if __name__ == "__main__":
    pass
